<template>
  <div class="chat-room">
    <div class="chat-header">
      <el-button icon="ArrowLeft" @click="goBack" text>返回</el-button>
      <span class="club-name">{{ clubName }}</span>
      <div class="ws-status" :class="wsStatus">
        <el-icon v-if="wsStatus === 'connected'"><CircleCheck /></el-icon>
        <el-icon v-else-if="wsStatus === 'connecting'"><Loading /></el-icon>
        <el-icon v-else><CircleClose /></el-icon>
        {{ wsStatus === 'connected' ? '已连接' : wsStatus === 'connecting' ? '连接中' : '未连接' }}
      </div>
    </div>
    
    <div class="chat-messages" ref="msgList" @scroll.passive="onScroll">
      <div v-if="loadingHistory" class="loading-more">
        <el-skeleton :rows="2" animated />
      </div>
      
      <div v-for="msg in messages" :key="msg.messageId" class="chat-message">
        <img :src="msg.avatar || 'https://ts1.tc.mm.bing.net/th/id/OIP-C.2cQ_To1lDx6cMF9eWNej0QHaFj?w=266&h=211&c=8&rs=1&qlt=70&o=7&cb=iavawebp1&pid=3.1&rm=3'" class="avatar" @error="handleAvatarError" />
        <div class="msg-content">
          <div class="msg-meta">
            <span class="nickname">{{ msg.nickName || '未知用户' }}</span>
            <span class="time">{{ formatTime(msg.createdAt) }}</span>
          </div>
          <div class="msg-text">{{ msg.content }}</div>
        </div>
      </div>
      
      <div v-if="messages.length === 0 && !loadingHistory" class="empty-messages">
        <el-empty description="暂无消息" />
      </div>
    </div>
    
    <div class="chat-input">
      <el-input
        v-model="input"
        placeholder="输入消息..."
        @keyup.enter.native="sendMsg"
        maxlength="500"
        show-word-limit
        type="textarea"
        :rows="3"
        resize="none"
      />
      <el-button type="primary" @click="sendMsg" :disabled="!input.trim()">发送</el-button>
    </div>
  </div>
</template>

<script setup name="ChatRoom">
import { getCurrentInstance, ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CircleCheck, CircleClose, Loading } from '@element-plus/icons-vue';
import { getClubChatHistory } from "@/api/system/clubs";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const route = useRoute();
const router = useRouter();

// 数据
const clubId = ref(route.params.clubId);
const clubName = ref(route.query.clubName || '群聊');
const messages = ref([]);
const input = ref('');
const ws = ref(null);
const loadingHistory = ref(false);
const pageNum = ref(1);
const pageSize = ref(20);
const finished = ref(false);
const reconnectTimer = ref(null);
const msgList = ref(null);
const wsStatus = ref('disconnected');

// 计算属性
const userId = computed(() => userStore.userId);
const nickname = computed(() => userStore.name);
const avatar = computed(() => userStore.avatar);

// 方法
function formatTime(time) {
  if (!time) return '';
  const d = new Date(time);
  const now = new Date();
  const diff = now - d;
  
  if (diff < 60000) { // 1分钟内
    return '刚刚';
  } else if (diff < 3600000) { // 1小时内
    return Math.floor(diff / 60000) + '分钟前';
  } else if (diff < 86400000) { // 1天内
    return Math.floor(diff / 3600000) + '小时前';
  } else {
    return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
  }
}

function handleAvatarError(e) {
  e.target.src = '/avatar.png';
}

function scrollToBottom() {
  proxy.$nextTick(() => {
    if (msgList.value) {
      msgList.value.scrollTop = msgList.value.scrollHeight;
    }
  });
}

function onScroll() {
  const list = msgList.value;
  if (list && list.scrollTop === 0 && !loadingHistory.value && !finished.value) {
    pageNum.value++;
    loadHistory(true);
  }
}

function loadHistory(prepend = false) {
  loadingHistory.value = true;
  getClubChatHistory(clubId.value, {
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }).then(response => {
    const rows = response.rows || [];
    if (rows.length < pageSize.value) {
      finished.value = true;
    }
    
    if (prepend) {
      messages.value = [...rows.reverse(), ...messages.value];
    } else {
      messages.value = rows.reverse();
      scrollToBottom();
    }
  }).catch(error => {
    console.error('加载历史消息失败:', error);
    proxy.$modal.msgError('加载历史消息失败');
  }).finally(() => {
    loadingHistory.value = false;
  });
}

function initWebSocket() {
  // 使用当前页面的协议和主机，但端口改为9000
  const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
  const host = window.location.hostname;
  
  // 检查用户信息
  if (!userId.value || !nickname.value) {
    console.error('User info incomplete:', { userId: userId.value, nickname: nickname.value });
    proxy.$modal.msgError('用户信息不完整，无法连接');
    return;
  }
  
  const wsUrl = `${protocol}://${host}:9000/ws`;
  
  console.log('Connecting to WebSocket:', wsUrl);
  console.log('User info for connection:', {
    clubId: clubId.value,
    userId: userId.value,
    nickname: nickname.value,
    avatar: avatar.value
  });
  
  wsStatus.value = 'connecting';
  
  ws.value = new WebSocket(wsUrl);
  
  ws.value.onopen = () => {
    console.log('=== WebSocket connected successfully ===');
    console.log('WebSocket readyState:', ws.value.readyState);
    console.log('WebSocket URL:', ws.value.url);
    wsStatus.value = 'connected';
    proxy.$modal.msgSuccess('已连接到群聊');
    
    // 延迟发送一条注册消息
    setTimeout(() => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        console.log('Sending test message after connection...');
        const testMsg = { clubId: clubId.value,userId:userId.value, nickname:nickname.value,avatar:avatar.value};
        ws.value.send(JSON.stringify(testMsg));
      } else {
        console.error('WebSocket not ready for sending message, readyState:', ws.value?.readyState);
      }
    }, 100);
  };
  
  ws.value.onmessage = (evt) => {
    try {
      const msg = JSON.parse(evt.data);
      if(msg.content){
      messages.value.push(msg);
      scrollToBottom();
      }

    } catch (error) {
      console.error('解析消息失败:', error, '原始数据:', evt.data);
    }
  };
  
  ws.value.onclose = (event) => {
    wsStatus.value = 'disconnected';
    proxy.$modal.msgWarning('连接断开，正在重连...');
    if (reconnectTimer.value) {
      clearTimeout(reconnectTimer.value);
    }
    reconnectTimer.value = setTimeout(() => {
      console.log('Attempting to reconnect...');
      wsStatus.value = 'connecting';
      initWebSocket();
    }, 3000);
  };
  
  ws.value.onerror = (error) => {
    console.error('=== WebSocket error ===');
    console.error('Error details:', error);
    wsStatus.value = 'error';
    proxy.$modal.msgError('连接失败，请检查网络');
  };
}

function sendMsg() {
  if (!input.value.trim()) {
    proxy.$modal.msgWarning('请输入消息内容');
    return;
  }
  
  if (!ws.value) {
    proxy.$modal.msgError('WebSocket未连接');
    return;
  }
  
  if (ws.value.readyState !== WebSocket.OPEN) {
    proxy.$modal.msgError('WebSocket连接已断开，正在重连...');
    return;
  }
  
  const msg = {
    content: input.value.trim()
  };
  
  try {
    console.log('Sending message:', msg);
    ws.value.send(JSON.stringify(msg));
    input.value = '';
  } catch (error) {
    console.error('发送消息失败:', error);
    proxy.$modal.msgError('发送消息失败');
  }
}

function goBack() {
  router.go(-1);
}

// 生命周期
onMounted(() => {
  console.log('ChatRoom mounted, user info:', {
    userId: userId.value,
    nickname: nickname.value,
    avatar: avatar.value,
    clubId: clubId.value,
    clubName: clubName.value
  });
  
  // 检查用户信息是否完整
  if (!userId.value) {
    console.error('userId is missing!');
    proxy.$modal.msgError('用户ID获取失败，请重新登录');
    return;
  }
  
  if (!nickname.value) {
    console.error('nickname is missing!');
    proxy.$modal.msgError('用户昵称获取失败');
    return;
  }
  
  loadHistory();
  initWebSocket();
});

onBeforeUnmount(() => {
  if (ws.value) {
    ws.value.close();
  }
  if (reconnectTimer.value) {
    clearTimeout(reconnectTimer.value);
  }
});
</script>

<style scoped>
.chat-room {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chat-header .el-button {
  margin-right: 12px;
}

.club-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.ws-status {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  margin-left: 12px;
}

.ws-status.connected {
  background: #f0f9ff;
  color: #67c23a;
}

.ws-status.connecting {
  background: #fef3c7;
  color: #e6a23c;
}

.ws-status.disconnected,
.ws-status.error {
  background: #fef2f2;
  color: #f56c6c;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f5f5f5;
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  color: #909399;
  font-size: 14px;
}

.chat-message {
  display: flex;
  margin-bottom: 16px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  flex-shrink: 0;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.msg-content {
  flex: 1;
  min-width: 0;
}

.msg-meta {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.nickname {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-right: 8px;
}

.time {
  font-size: 12px;
  color: #909399;
}

.msg-text {
  font-size: 14px;
  line-height: 1.5;
  background: #fff;
  padding: 12px 16px;
  border-radius: 12px;
  display: inline-block;
  max-width: 70%;
  word-break: break-word;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  border: 1px solid #e4e7ed;
}

.empty-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.chat-input {
  display: flex;
  align-items: flex-end;
  padding: 16px;
  background: #fff;
  border-top: 1px solid #e4e7ed;
  gap: 12px;
}

.chat-input .el-input {
  flex: 1;
}

.chat-input .el-button {
  height: 80px;
  padding: 0 20px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>